package pl.squeaky.mvc.dialog;

import java.util.ArrayList;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;

public class FolderSelectionDialog extends ElementTreeSelectionDialog {
	
	static class ContentProvider implements ITreeContentProvider {
		IContainer folder;
		
		public ContentProvider(IContainer folder) {
			this.folder = folder;
		}
		
		@Override
		public Object[] getChildren(Object parentElement) {
			if(parentElement instanceof IContainer) {
				IContainer container = (IContainer)parentElement;
				ArrayList<IFolder> folders = new ArrayList<IFolder>();
				try {
					for(IResource resource : container.members()) {
						if(resource instanceof IFolder) {
							folders.add((IFolder)resource);
						}
					}
				} catch (CoreException e) {
					throw new RuntimeException(e);
				}
				
				return folders.toArray();
			}
			
			return new Object[0];
		}

		@Override
		public Object getParent(Object element) {
			if(element instanceof IResource) {
				IResource resource = (IResource)element;
				return resource.getParent();
			}
			
			return null;
		}

		@Override
		public boolean hasChildren(Object element) {
			return true;
		}

		@Override
		public Object[] getElements(Object inputElement) {
			return new Object[] {folder};
		}

		@Override
		public void dispose() {	
		}

		@Override
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		}
	}
	
	static class ViewLabelProvider extends LabelProvider {
		@Override
		public String getText(Object element) {
			if(element instanceof IResource) {
				IResource resource = (IResource)element;
				
				return resource.getName();
			}
			
			return null;
		}
		
		@Override
		public Image getImage(Object element) {
			if(element instanceof IProject) {
				return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_PROJECT);
			} else if(element instanceof IFolder) {
				return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER);
			}
			
			return null;
		}
	}
	
	public FolderSelectionDialog(Shell parent, IContainer folder) {
		super(parent, new ViewLabelProvider(), new ContentProvider(folder));
		
		setInput(this);
		setTitle("Choose path");
		setImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER));
	}
}
